package com.blockmeta.bbs.businesslibrary.util;

import android.content.Context;
import android.os.Handler;

import com.blankj.utilcode.util.LogUtils;

import com.alibaba.fastjson.JSON;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.security.AESPKCS7Util;
import com.blockmeta.bbs.baselibrary.utils.security.RSAUtil;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.pojo.PublicKeyRequestPOJO;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.retrofit.api.InterfaceGetPublicKey;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;

import io.reactivex.subscribers.ResourceSubscriber;

import static com.blockmeta.bbs.businesslibrary.constant.Constant.ORIGNKEY;
import static com.blockmeta.bbs.businesslibrary.launch.ResourceDownload.MSG_CONFIRM_CHANNEL_OK;
import static com.blockmeta.bbs.businesslibrary.launch.ResourceDownload.MSG_GET_BUNDLE;

public class GateWayUtil {
    public static String getGateAuth() {
        //统一网关鉴权
        String orignKey = SharedPreferenceUtil.getString(BaseApp.getApp(), Constant.GATE_KEY, ORIGNKEY);
        String nowVersion = SharedPreferenceUtil.getString(BaseApp.getApp(), Constant.SECRET_KEY_VERSION, "1");
        PublicKeyRequestPOJO pojo = PublicKeyRequestPOJO.newBuilder()
                .appId(Constant.APP_ID)
                .timestamp(String.valueOf(System.currentTimeMillis() / 1000))
                .serverCode("0")
                .build();
        String authorization = "";
        try {
            authorization = RSAUtil.encode(JSON.toJSONString(pojo), orignKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PublicKeyRequestPOJO pojoRequest = PublicKeyRequestPOJO.newBuilder()
                .appId(Constant.APP_ID)
                .secretKeyVersion(nowVersion)
                .sign(authorization)
                .build();
        return JSON.toJSONString(pojoRequest);
    }

    public static void getPublicKey(final Context context, final Handler handler) {


        String nowVersion = SharedPreferenceUtil.getString(context, Constant.SECRET_KEY_VERSION, "1");
        PublicKeyRequestPOJO pojo = PublicKeyRequestPOJO.newBuilder()
                .secretKeyVersion(nowVersion)
                .appId(Constant.APP_ID)
                .build();
        RetrofitFactory.getRootRetrofit().create(InterfaceGetPublicKey.class)
                .needChangeSecretKey(pojo)
                .compose(RxUtil.<BaseCodeResponse<Boolean>>rxSchedulerHelper())
                .compose(RxUtil.<Boolean>commonResultByCode())
                .retryWhen(new RxUtil.RetryWithDelay(3, 2000))
                .subscribe(new ResourceSubscriber<Boolean>() {
                    @Override
                    public void onNext(Boolean needUpdate) {
                        if (needUpdate) {
                            updatePublicKey(context, handler);
                        } else {
                            handler.sendEmptyMessage(MSG_GET_BUNDLE);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        LogUtils.e("author", "获取不到publickkey版本");
                        //虽然失败，但是为了保证使用还是下去
                        handler.sendEmptyMessage(MSG_GET_BUNDLE);

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public static void updatePublicKey(final Context context, final Handler handler) {
        final String secretKey = SharedPreferenceUtil.getString(context, Constant.GATE_KEY, Constant.ORIGNKEY);
        String secretKeyVersion = SharedPreferenceUtil.getString(context, Constant.SECRET_KEY_VERSION, "1");

        String time = String.valueOf(System.currentTimeMillis() / 1000);
        PublicKeyRequestPOJO pojo = PublicKeyRequestPOJO.newBuilder()
                .secretKeyVersion(secretKeyVersion)
                .appId(Constant.APP_ID)
                .secretPublicKey(secretKey)
                .timestamp(time)
                .build();
        String encrypt = AESPKCS7Util.encrypt(JSON.toJSONString(pojo), AESPKCS7Util.CRYPT_KEY);
        String magicKey = "";
        try {
            magicKey = RSAUtil.encode(AESPKCS7Util.CRYPT_KEY, secretKey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        PublicKeyRequestPOJO pojoRequest = PublicKeyRequestPOJO.newBuilder()
                .secretKeyVersion(secretKeyVersion)
                .appId(Constant.APP_ID)
                .msg(encrypt)
                .magicKey(magicKey)
                .build();
        RetrofitFactory.getRootRetrofit().create(InterfaceGetPublicKey.class)
                .changePublicSecretKey(pojoRequest)
                .compose(RxUtil.<BaseCodeResponse<String>>rxSchedulerHelper())
                .compose(RxUtil.<String>commonResultByCode())
                .retryWhen(new RxUtil.RetryWithDelay(3, 2000))
                .subscribe(new ResourceSubscriber<String>() {
                    @Override
                    public void onNext(String encryptWord) {
                        if (!encryptWord.contains(",")) {
                            LogUtils.e("author", "请求新的encryptWord不含,");
                            return;
                        }
                        String[] split = encryptWord.split(",");
                        if (split.length != 2) {
                            LogUtils.e("author", "请求新的encryptWord不合法");
                            return;
                        }
                        try {
                            String aesKey = RSAUtil.decodePublic(split[1], secretKey);
                            String decrypt = AESPKCS7Util.decrypt(split[0], aesKey);
                            PublicKeyRequestPOJO newVersion = JSON.parseObject(decrypt, PublicKeyRequestPOJO.class);
                            if (newVersion != null) {
                                SharedPreferenceUtil.putString(context, Constant.GATE_KEY, newVersion.getSecretPublicKey());
                                SharedPreferenceUtil.putString(context, Constant.SECRET_KEY_VERSION, newVersion.getSecretKeyVersion());
                                handler.sendEmptyMessage(MSG_GET_BUNDLE);
                            } else {
                                LogUtils.e("author", "解密得到的pojo为空");
                            }
                        } catch (Exception e) {
                            LogUtils.e("author", "解密encryptWord失败");
                            onError(e.getCause());
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        LogUtils.e("author", "请求新的gate public secret失败");

                    }

                    @Override
                    public void onComplete() {
                    }
                });


    }
}
